//-----------------------------------------------------------------------------
// Copyright (c) BaFang Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

using System;
using System.IO;
using System.Xml.Serialization;
using BaFangSpider;

    /// <summary>
    /// Summary description for DataManager
    /// </summary>
    public class DataManager
    {
        string fileName;
        Type type;
        static string baseFilepath = "App_Data";

        public static string BaseFilePath
        {
            get
            {
                return baseFilepath;
            }
        }

        public DataManager(string fileName, Type type)
        {
            this.fileName = Path.Combine(baseFilepath, fileName);
            this.type = type;
        }

        public object LoadData()
        {
            if (File.Exists(this.fileName))
            {
                using (FileStream stream = new FileStream(this.fileName, FileMode.Open))
                {
                    XmlSerializer serializer = new XmlSerializer(this.type);
                    object data = serializer.Deserialize(stream);
                    return data;
                }
            }
            return null;
        }

        public void SaveData(object data)
        {
            try
            {
                if (File.Exists(this.fileName))
                {
                    File.Delete(this.fileName);
                }
                using (FileStream stream = new FileStream(this.fileName, FileMode.OpenOrCreate))
                {
                    XmlSerializer serializer = new XmlSerializer(this.type);
                    serializer.Serialize(stream, data);
                }
            }
            catch (Exception e)
            {
                Logger logger = Logger.GetLogger();
                logger.Write(DateTime.Now.ToString() + ":Save file fail.filename:" + this.fileName + e.Message);
            }
        }
    }

